import redis, { RedisClient } from 'redis';
import { Nohm as nohm } from 'nohm';
import { promiseTimeout } from './tools';

export let redisClient: RedisClient;
export const initRedis = async Config => {
	redisClient = redis.createClient(Config.getRedis());
	return await promiseTimeout(
		1000,
		new Promise((fill, reject) => {
			redisClient.once('ready', () => {
				nohm.setClient(redisClient);
				nohm.setPrefix(Config.getRedisNohmPrefix());
				fill(true);
			});
			redisClient.once('error', reject);
		}),
		'connect redis timeout',
	).catch(e => {
		console.log('!!!!!!!!!!!!!!!', 'connect redis error', e);
		redisClient.quit();
		return false;
	});
};

export let clearPattern = async pat => {
	await new Promise(fill => {
		redisClient.eval(
			"return redis.call('del', unpack(redis.call('keys', ARGV[1])))",
			0,
			pat,
			fill,
		);
	});
};
